package com.ruoyi.web.resolver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.xml.XMLConstants;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.springframework.core.io.ClassPathResource;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class LocalResolver implements EntityResolver {

    private final static String MYBATIS_CONFIG_DTD = "org/apache/ibatis/builder/xml/mybatis-config.dtd";

    @Override
    public InputSource resolveEntity(String publicId, String systemId)
        throws SAXException, IOException {

        if (systemId != null && systemId.contains(MYBATIS_CONFIG_DTD)) {
            InputStream inputStream = new ClassPathResource(MYBATIS_CONFIG_DTD).getInputStream();
            return new InputSource(new BufferedReader(new InputStreamReader(inputStream)));
        }
        return null;
    }

    public static XNode parse(InputStream inputStream) throws IOException {
        XPathParser xPathParser = new XPathParser(inputStream, false, null, new LocalResolver());
        return xPathParser.evalNode("/configuration");
    }
}
